<template>
	<view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
		<!--导航栏-->
		<pageLayout
			:barTitle="title"
			:isSearchNull="isSearchNull"
			:isOpen="isOpen"
			@rightClick="clickSearch">
		</pageLayout>
		<!--查询弹窗-->
		<up-popup :z-index="90" :show="isOpen" @close="closeSearch" mode="top">
			<view @touchmove.stop.prevent>
			<scroll-view class="search" scroll-y="true" @touchmove.stop>
				<view class="search-form">
					<uni-forms ref="searchRef" :modelValue="searchModel" label-width="160rpx">
						<uni-forms-item label="区域">
							<uni-data-select
								v-model="searchModel.regionCode"
								placeholder="请选择区域"
								:localdata="setStore.allProvinceList"></uni-data-select>
						</uni-forms-item>
						<uni-forms-item label="商品名称">
							<uni-easyinput v-model="searchModel.name" placeholder="请输入商品名称" />
						</uni-forms-item>
						<uni-forms-item label="类型名称">
							<uni-easyinput v-model="searchModel.typeName" placeholder="请输入类型名称" />
						</uni-forms-item>
						<uni-forms-item label="商品编码">
							<uni-easyinput v-model="searchModel.code" placeholder="请输入商品编码" />
						</uni-forms-item>
						<uni-forms-item label="商品条码">
							<uni-easyinput v-model="searchModel.barcode" placeholder="请输入商品条码" />
						</uni-forms-item>
						<uni-forms-item label="商品归类">
							<uni-data-select
								v-model="searchModel.productClassify"
								placeholder="请选择商品归类"
								:localdata="productClassifyList"></uni-data-select>
						</uni-forms-item>
						<uni-forms-item label="商品状态">
							<view class="search-form-checkbox main-flex">
								<uni-data-checkbox v-model="searchModel.status" :localdata="[
									{ value: 0, text: '下架'},
									{ value: 1, text: '上架'}
								]" />
							</view>
						</uni-forms-item>
						<uni-forms-item label="是否样品">
							<view class="search-form-checkbox main-flex">
								<uni-data-checkbox v-model="searchModel.trialProduct" :localdata="[
									{ value: 0, text: '否'},
									{ value: 1, text: '是'}
								]" />
							</view>
						</uni-forms-item>
						<uni-forms-item label="销售需求">
							<view class="search-form-checkbox main-flex">
								<uni-data-checkbox v-model="searchModel.salesDemand" :localdata="[
									{ value: 0, text: '否'},
									{ value: 1, text: '是'}
								]" />
							</view>
						</uni-forms-item>
						<uni-forms-item label="是否冻结">
							<view class="search-form-checkbox main-flex">
								<uni-data-checkbox v-model="searchModel.freeze" :localdata="[
									{ value: 0, text: '否'},
									{ value: 1, text: '是'}
								]" />
							</view>
						</uni-forms-item>
						<uni-forms-item label="采购商品">
							<view class="search-form-checkbox main-flex">
								<uni-data-checkbox v-model="searchModel.purchaseFlag" :localdata="[
									{ value: 0, text: '否'},
									{ value: 1, text: '是'}
								]" />
							</view>
						</uni-forms-item>
					</uni-forms>
					<view class="search-footer main-flex">
						<up-button
							class="search-footer-item"
							text="搜索"
							type="primary"
							@click="searchSubmit"
							icon="search"></up-button>
						<up-button
							class="search-footer-item"
							@click="resetSubmit"
							text="重置"></up-button>
					</view>
				</view>
			</scroll-view>
			</view>
		</up-popup>
		<view class="content">
			<!--内容-->
			<view class="table">
				<ty-table
					:data="tableList"
					:columns="columns"
					:sortable="true"
					@row-click="rowClick"
					:cellClassName="() => 'table-cell'"
					:headerCellClassName="() => 'table-cell'"
					:rowClassName="() => 'table-row'"
					:isOperateBtn="(row) => {
						return checkPermi(['zhouyz:productInfo:updateStatus'])
						|| (checkPermi(['zhouyz:productInfo:exceptionPutaway']) && row.status === 0)
					}"
					stripe
					border>
					<template v-slot:before="{ row }">
						<view class="table-td-before table-cell table-td-row goods main-flex">
							<view class="goods_l" @click.stop="previewImg('', row.bannerList)">
								<up-image width="110rpx" height="110rpx" :src="row.image" :lazy-load="true"></up-image>
							</view>
							<view class="goods_c main-flex-item">
								<view class="table-td-row">名称：<text class="table-td-text">{{row.name}}</text></view>
								<view class="table-td-row">编码：<text class="table-td-text">{{row.code}}</text></view>
								<view class="table-td-row">条码：<text class="table-td-text">{{row.barcode}}</text></view>
							</view>
							<view class="goods_r">
								<view class="table-td-row">
									状态：
									<uni-tag :type="row.status === 1 ? 'success' : 'error'" size="small" :text="row.status === 1 ? '上架' : '下架'" />
								</view>
								<view class="detail-text">
									存货编码：
									<text class="red">{{row.storeCode}}</text>
								</view>
								<view class="detail-text">
									存储类型：
									<uni-tag :class="`storeType${row.storeType}`" size="small" :text="arrText(storeTypeList, row.storeType)" />
								</view>
							</view>
						</view>
					</template>
					<template v-slot:goods="{ row }">
						<view class="table-td-cell">
							<!-- <view class="table-td-row">ID：<text class="table-td-text">{{row.id}}</text></view> -->
							<view class="table-td-row">区域：<text class="table-td-text">{{arrText(setStore.allProvinceList, row.regionCode)}}</text></view>
							<view class="table-td-row">类型：<text class="table-td-text">{{row.typeName}}</text></view>
							<view class="table-td-row">单位：<text class="table-td-text">{{row.unit}}</text></view>
							<!-- <view class="table-td-row">销量：<text class="table-td-text">{{row.salesNumber}}</text></view> -->
							<!-- <view class="table-td-row">库存：<text class="table-td-text">{{row.stock}}</text></view> -->
							<view class="table-td-row main-flex">归类：<uni-tag size="small" :text="arrText(productClassifyList, row.productClassify)" /></view>
						</view>
					</template>
					<template v-slot:money="{ row }">
						<view class="table-td-cell">
							<view class="table-td-row" v-if="checkPermi(['zhouyz:purchaseOrder:price'])">采购：<text class="table-td-text">{{row.purchasePrice}}</text></view>
							<!-- <view class="table-td-row">最低：<text class="table-td-text">{{row.sellPrice}}</text></view> -->
							<view class="table-td-row" v-if="checkPermi(['zhouyz:productPrice:list'])">批发：<text class="table-td-text">{{row.wholePrice}}</text></view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:productPrice:list'])">零售：<text class="table-td-text">{{row.retailPrice}}</text></view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:productPrice:list'])">团购：<text class="table-td-text">{{row.groupPrice}}</text></view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:productPrice:list'])">超市：<text class="table-td-text">{{row.shopPrice}}</text></view>
							<!-- <view class="table-td-row">市场价：<text class="table-td-text">{{row.marketPrice}}</text></view> -->
						</view>
					</template>
					<template v-slot:status="{ row }">
						<view class="table-td-cell">
							<view class="table-td-row main-flex">推荐：<uni-tag size="small" :type="row.recommend === 1 ? 'success' : ''" :text="row.recommend === 1 ? '推荐' : '不推荐'" /></view>
							<!-- <view class="table-td-row main-flex">
								积分：
								<uni-tag size="small" :type="row.sendIntegralFlag === 1 ? 'success' : ''" :text="row.sendIntegralFlag === 1 ? '是' : '否'" />
								<text class="table-td-text">(送{{row.sendIntegralValue}}，最多{{row.mastSendIntegral}})</text>
							</view> -->
							<view class="table-td-row main-flex">
								是否采购：
								<uni-tag size="small" :type="row.purchaseFlag === 1 ? 'success' : ''" :text="row.purchaseFlag === 1 ? '是' : '否'" />
							</view>
							<view class="table-td-row main-flex" @click.stop>
								是否样品：
								<uni-tag size="small" :type="row.trialProduct === 1 ? 'success' : ''" :text="row.trialProduct === 1 ? '是' : '否'" />
							</view>
							<view class="table-td-row main-flex" @click.stop>
								销售可提：
								<uni-tag size="small" :type="row.salesDemand === 1 ? 'success' : ''" :text="row.salesDemand === 1 ? '是' : '否'" />
							</view>
							<view class="table-td-row main-flex" @click.stop>
								是否冻结：
								<uni-tag size="small" :type="row.freeze === 1 ? 'error' : ''" :text="row.freeze === 1 ? '是' : '否'" />
							</view>
						</view>
					</template>
					<template v-slot:operate="{ row }">
						<view class="table-td-operate table-cell table-td-row main-flex">
							<view class="table-operate-btn main-flex" v-if="checkPermi(['zhouyz:productInfo:updateStatus'])">
								<up-button
									class="table-operate-btn main-flex"
									size="mini"
									:type="row.status === 1 ? 'error' : 'primary'"
									@click.stop="updateProductFun(row)">
									<uni-icons class="table-operate-btn-icon" :type="row.status === 1 ? 'arrow-down' : 'arrow-up'" size="20rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">{{row.status === 1 ? '下架' : '上架'}}</view>
								</up-button>
							</view>
							<view class="table-operate-btn main-flex" v-if="checkPermi(['zhouyz:productInfo:exceptionPutaway']) && row.status === 0">
								<up-button
									class="table-operate-btn main-flex"
									size="mini"
									type="warning"
									@click.stop="updateProductExceptionFun(row)">
									<uni-icons class="table-operate-btn-icon" type="arrow-up" size="20rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">异常上架</view>
								</up-button>
							</view>
							<view class="table-operate-btn main-flex" v-if="checkPermi(['zhouyz:productInfo:edit'])">
								<up-button
									size="mini"
									type="primary"
									@click.stop="add(row.id)">
									<uni-icons class="table-operate-btn-icon" type="compose" size="24rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">修改</view>
								</up-button>
							</view>
						</view>
					</template>
					<template v-slot:empty>
						<view class="table-empty">
							<up-empty mode="data"/>
						</view>
					</template>
				</ty-table>
			</view>
			<!--分页-->
			<view class="pagination" v-show="total > 0">
				<ty-pagination
					:total="total"
					:pageSize="pageSize"
					:currentPage="pageNum"
					:pageSizes="[10, 20, 30, 50]"
					mode="simple"
					layout="first,prev,page,next,last"
					@sizeChange="sizeChange"
					@change="pageChange">
				</ty-pagination>
			</view>
		</view>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref, getCurrentInstance, watch } from 'vue';
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import { allProvince } from "@/api/erp_api/region"
import { productInfo, updateProductStatus, productType } from "@/api/erp_api/product"
import { isObjectEmptySimple, copyText, arrText, previewImg } from '@/utils/ty.js';
import { productClassifyList, storeTypeList } from '@/utils/config.js';
import useUserStore from '@/store/modules/user';
import useSetStore from '@/store/modules/set';
import { Decimal } from 'decimal.js'

	const userStore = useUserStore()
	const setStore = useSetStore()
	const { proxy } = getCurrentInstance()

	// 标题设置
	const title = ref('')
	onLoad((option) => {
		title.value = getTitle(userStore.menu)
		uni.setNavigationBarTitle({
			title: title.value 
		})
		uni.$on('refreshList', () => {
			getList()
		})
	})
	
	// 获取商品类别
	const productTypeList = ref([])
	const getProductType = () => {
		return productType().then(res => {
			productTypeList.value = res.rows.map(item => {
				return {
					...item,
					value: item.id,
					text: item.name
				}
			}) || []
		})
	}
	
	// 搜索相关
	const isSearchNull = ref(true)
	const isOpen =  ref(false)
	const clickSearch = (val) => {
		isOpen.value = val
	}
	const closeSearch = (val) => {
		isOpen.value = false
	}
	// 确认搜索
	const searchRef = ref(null)
	const searchModel = ref({
		regionCode: '',
		name: '',
		typeName: '',
		code: '',
		barcode: '',
		productClassify: '',
		status: '',
		trialProduct: '',
		salesDemand: '',
		freeze: 0,
		purchaseFlag: '',
		productWeight: ''
	})
	const searchSubmit = () => {
		pageNum.value = 1
		tableList.value = []
		isOpen.value = false
		searchFirst()
	}
	// 重置搜索
	const resetSubmit = () => {
		// searchRef.value.resetFields()
		searchModel.value = {
			regionCode: '',
			name: '',
			typeName: '',
			code: '',
			barcode: '',
			productClassify: '',
			status: '',
			trialProduct: '',
			salesDemand: '',
			freeze: 0,
			purchaseFlag: '',
			productWeight: ''
		}
		if (userStore.regionCode) {
			searchModel.value.regionCode = userStore.regionCode
		}
		isSearchNull.value = true
		isOpen.value = false
		searchFirst()
	}
	
	
	// 数据查询
	const pageNum = ref(1)
	const pageSize = ref(10)
	const total = ref(0)
	const tableList = ref([])
	const isLoading = ref(false)
	
	// 表格头部
	const columns = ref([
		{ title: '商品信息', key: 'goods' },
		{ title: '价格', key: 'money' },
		{ title: '状态', key: 'status' }
	])
	
	// 从第一页查询
	const searchFirst = () => {
		pageNum.value = 1
		tableList.value = []
		isSearchNull.value = isObjectEmptySimple(searchModel.value)
		getList()
	}
	//页数切换
	const pageChange = (page) => {
		pageNum.value = page
		getList()
	}
	//每页条数切换
	const sizeChange = (size) => {
		pageSize.value = size
		getList()
	}
	
	const getList = () => {
		const params = {
			pageNum: pageNum.value,
			pageSize: pageSize.value,
			productWeight: 0,
			sortKey: 0
		}
		if (searchModel.value.regionCode) {
			params.regionCode = searchModel.value.regionCode
		}
		if (searchModel.value.name) {
			params.name = searchModel.value.name
		}
		if (searchModel.value.typeName) {
			params.typeName = searchModel.value.typeName
		}
		if (searchModel.value.code) {
			params.code = searchModel.value.code
		}
		if (searchModel.value.barcode) {
			params.barcode = searchModel.value.barcode
		}
		if (searchModel.value.status || searchModel.value.status === 0) {
			params.status = searchModel.value.status
		}
		if (searchModel.value.trialProduct || searchModel.value.trialProduct === 0) {
			params.trialProduct = searchModel.value.trialProduct
		}
		if (searchModel.value.salesDemand || searchModel.value.salesDemand === 0) {
			params.salesDemand = searchModel.value.salesDemand
		}
		if (searchModel.value.freeze || searchModel.value.freeze === 0) {
			params.freeze = searchModel.value.freeze
		}
		if (searchModel.value.purchaseFlag || searchModel.value.purchaseFlag === 0) {
			params.purchaseFlag = searchModel.value.purchaseFlag
		}
		if (searchModel.value.productClassify || searchModel.value.productClassify === 0) {
			params.productClassify = searchModel.value.productClassify
		}
		isLoading.value = true
		uni.showLoading({
			title: '数据加载中...'
		})
		productInfo(params).then(res => {
			tableList.value = res.rows.map(item => {
				return {
					...item,
					bannerList: item.banner.split(',').filter(item => item)
				}
			}) || []
			total.value = res.total
			isLoading.value = false
			uni.hideLoading()
    }).catch(() => {
			isLoading.value = false
			uni.hideLoading()
		})
	}
	
	// 点击行
	const rowClick = (row) => {
		uni.navigateTo({
			url: `/pages/product/productDetail?id=${row.id}`
		})
	}
	
	//编辑
	const add = (id) => {
		uni.navigateTo({
			url: id ? `/pages/product/productEdit?id=${id}` : '/pages/product/productEdit'
		})
	}
	
	const getGrossProfit = (row) => {
		let grossProfit = 0.15
		if (row.productClassify === 1) {
			const typeFilter = productTypeList.value.filter(item => item.id == row.typeId)
			grossProfit = typeFilter?.[0]?.grossProfit || 0.15
		} else {
			grossProfit = 0.09
		}
		return 1 - grossProfit
	}
	const isException = (row, grossProfit) => {
		const min = (parseFloat(row.purchasePrice) / grossProfit).toFixed(2)
		return min > row.sellPrice
		|| row.sellPrice > row.wholePrice
		|| row.sellPrice > row.retailPrice
		|| row.sellPrice > row.groupPrice
		|| row.sellPrice > row.shopPrice
	}
	
	// 上下架
	const isSubmit = ref(false)
	const updateProductFun = (row) => {
		const grossProfit = getGrossProfit(row)
		if (isException(row, grossProfit) && row.status === 0) {
			let str = `ID:${row.id}，品名:${row.name}，价格异常，上架失败！`
			str = `ID:${row.id}，品名:${row.name}，价格异常，毛利不到${Decimal(1).sub(Decimal(grossProfit)).toNumber()}，上架失败！`
			uni.showModal({
				content: str,
				showCancel: false,
				success: (res) => {
					if (res.confirm) {
					}
				}
			})
		} else {
			
			let str = `是否确认${row.status === 1 ? '下架':'上架'}ID:【${row.id}】品名:【${row.name}】的商品？`
			uni.showModal({
				content: str,
				success: (res) => {
					if (res.confirm) {
						updateProductStatusFun({
							id: row.id,
							status: row.status === 1 ? 0 : 1
						})
					}
				}
			})
		}
	}
	const updateProductExceptionFun = (row) => {
		let str = `商品价格异常，是否确认上架ID:【${row.id}】品名:【${row.name}】的商品?`
		uni.showModal({
			content: str,
			success: (res) => {
				if (res.confirm) {
					updateProductStatusFun({
						id: row.id,
						status: 1
					})
				}
			}
		})
	}
	const updateProductStatusFun = (params) => {
		if (isSubmit.value) return false
		isSubmit.value = true
		updateProductStatus(params).then(res => {
			modal.showToast(res.msg)
			getList()
			isSubmit.value = false
		}).catch(() => {
			isSubmit.value = false
		})
	}
	watch(() => userStore.regionCode, (nval, oval) => {
		if (nval) {
			searchModel.value.regionCode = userStore.regionCode
			searchFirst()
		}
	})
	onMounted(async () => {
		await getProductType()
		searchFirst()
	})
</script>

<style scoped lang="scss">
.goods {
	align-items: flex-start;
	&_c {
		padding: 0 20rpx;
	}
	&_r {
		width: 240rpx;
		align-self: center;
		padding: 0 20rpx;
		.uni-tag {
			font-weight: 600;
		}
	}
}
.storeType1 {
	background-color: #FFA726;
	border-color: #FFA726;
}
.storeType2 {
	background-color: #4FC3F7;
	border-color: #4FC3F7;
}
.storeType3 {
	background-color: #B3E5FC;
	border-color: #B3E5FC;
}
</style>
